﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.Net.Sockets;

namespace ClockSync
{
    class Slave
    {
        private RunningClock clock;
        private Neighbour master;
        private Neighbour self;
        //private tcpServer ser;
       // private tcpClient cli;
        System.Threading.Thread clockThread;
        NeighbourTable ntb;
        public Slave(NeighbourTable ntb, RunningClock clock)
        {
            this.clock = clock;           
            this.master = ntb.getMaster();
            //ser = new tcpServer(IPAddress.Any,9000);
            this.ntb = ntb;

            foreach (Neighbour n in ntb.Neighbours)
            {
                 if (n.Address.Equals(utils.FindLanAddress())){
                     self = n;
                     n.tcpHandler = new TcpHandler(this.master.Address, this.master.getPort, this.master.sendPort);
                     break;
                 }
            }
        }

        public void start()
        {
            byte[] offset;
           
            
            while (true)
            {
                Console.WriteLine("top of while");
                string msg = utils.ByteToStrArray(master.tcpHandler.getMsg());
                Console.WriteLine("\tslave recived msg:\" " + msg + "\"");
                if (msg.Equals("!!!"))
                {
                   self.tcpHandler.sendMsg(clock.getTime());
                    Console.WriteLine("\tslave sent msg:\" " + clock.getTime() + "\"");
                }

                offset = master.tcpHandler.getMsg();

                Console.WriteLine("\tslave recived msg:\" " + offset + "\"");

                Console.WriteLine("slave's offset should be:" + offset+"his old time was: "+clock.getTime());
                
                string srtOffset = utils.ByteToStrArray(offset);
                Console.WriteLine("\tstr offset: " + srtOffset);
                
                int intOffset = int.Parse(srtOffset);
                Console.WriteLine("\tintOffset = " + intOffset);

                //int.Parse(utils.ByteToStrArray(offset).Substring(0,5))
                clock.setTime(intOffset);
                Console.WriteLine("\tslave's time after adding offet is:"+clock.getTime());
            }

        }

    }
}
